// pages/goods_detail/index.js

// 轮播图点击预览大图
// 给轮播图绑定点击事件
// 调用小程序的api   previewImage

import { request } from '../../request/index.js'

import regeneratorRuntime from '../../lib/runtime/runtime';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        goodsObj: {}
    },

    // 商品对象
    GoodsInfo: {},
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        const { goods_id } = options
        // console.log(goods_id);
        this.getGoodsDetail(goods_id)
    },

    // 获取商品的详情数据
    async getGoodsDetail(goods_id){
        const res = await request({url: "/goods/detail", data: {goods_id}})
        // console.log(res);
        this.GoodsInfo = res

        this.setData({
            goodsObj: {
                goods_name: res.goods_name,
                goods_price: res.goods_price,
                goods_introduce: res.goods_introduce.replace(/\.webp/g, '.jpg'),
                pics: res.pics
            }
        })
    },


    // 点击轮播图放大预览
    handlePreviewImage(e){
        // 先构造要预览的图片数组
        const urls = this.GoodsInfo.pics.map((item)=>{
            return item.pics_mid
        })

        // 接收传递过来的图片url
        const current = e.currentTarget.dataset.url

        wx.previewImage({
            current: current,
            urls: urls,
        })
    },



    // 点击加入购物车
    handleCartAdd(){
        // 1.先获取缓存中的购物车
        let cart = wx.getStorageSync("cart") || [];
        // 2.判断商品对象是否存在于购物车数组中
        let index = cart.findIndex(item=>item.goods_id === this.GoodsInfo.goods_id)
        if(index === -1){
            // 不存在
            this.GoodsInfo.num = 1;
            this.GoodsInfo.checked = true;
            cart.push(this.GoodsInfo);
        }else{
            // 存在
            cart[index].num++;
        }

        // 把购物车重新添加回缓存中
        wx.setStorageSync("cart", cart);
        
        // 弹窗提示
        wx.showToast({
            title: '加入成功',
            icon: 'success',
            mask: true,
        });
          
    }
})